import axios from '@/libs/api.request'
import Vue from 'vue'
import Router from 'vue-router'
import routerlink from './routers'
import store from '@/store'
import iView from 'iview'
import { getToken, canTurnTo } from '@/libs/util'

Vue.use(Router)
var user = localStorage.getItem('user')
let routes = []
if(user && JSON.parse(user).type == 1){
    user = JSON.parse(user)
    routes = routerlink.filter(item => {
        return (item.meta.user_type == user.type || item.name === 'login')
    })
} else {
    routes = routerlink
}
const router = new Router({
    routes,
	mode: 'history',
})
const LOGIN_PAGE_NAME = 'login'
const REGISTER_PAGE_NAME = 'register'

const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error=> error)
}

router.beforeEach((to, from, next) => {
	iView.LoadingBar.start()
	// localStorage里面的用户解析存到全局store里面去
	let token = ''
    console.log(localStorage.getItem('user'))
	if (localStorage.getItem('user')) {
		let token = JSON.parse(localStorage.getItem('user'))
		store.commit('setUserId', token.id)
		store.commit('setUserName', token.username)
		store.commit('setToken', token.token)
    store.commit('setType', token.type)
    store.commit('setAvator', token.icon)
		store.commit('setRole', token.role)
		store.commit('setFirstAccess', token.first_access)
		let obj = {}
		const res = axios.request({
	        url: '/backend/permission/get-user-auth?user_token='+token.token,
	        method: 'get',
	    })
	    //console.log(res)
		res.then(
			function (result) {
				store.commit('setAccess', result.data)
			}
		)
	}
  if (!localStorage.getItem('user') && to.name === 'login') {
		// 跳转到注册页
		next();
	} else if (!localStorage.getItem('user') && to.name !== 'login') {
		// 未登录且要跳转的页面不是登录页
		next({
			name: 'login', // 跳转到登录页
		})
	} else if (localStorage.getItem('user') && (to.name === 'login')) {
    // 已登录且要跳转的页面是登录页
    next({
        name: 'good_list', // 跳转到home页
    })
	} else {
		next()
	}
})

router.afterEach(to => {
	iView.LoadingBar.finish()
	window.scrollTo(0, 0)
})

export default router
